//
//  ShenPiXiaoXiViewController.m
//  JuBoCRM
//
//  Created by iMac on 2024/2/1.
//  Copyright © 2024 iningKe. All rights reserved.
//

#import "ShenPiXiaoXiViewController.h"
#import "ShenPiXiaoXiTableViewCell.h"
#import "ShenPiXiangQingViewController.h"
#import "KeHuXiangQingViewController.h"

#import "LingQuXiaoXiTableViewCell.h"
#import "LanHaiXiaoXiTableViewCell.h"

#import "AlertRemindView.h"
#import "GongHaiKeHuXiangQingViewController.h"

#import "QuanYuXiaoXiTableViewCell.h"
@interface ShenPiXiaoXiViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>{
    int page;
    NSMutableArray *dataSource;
    
    BOOL isFirst;
}
@property (weak, nonatomic) IBOutlet TPKeyboardAvoidingTableView *mainTableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSpace;

@end

@implementation ShenPiXiaoXiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
    
    if(_isShenPi){
        self.customNavBar.title = @"审批消息";
    }else{
        self.customNavBar.title = @"客户消息";
    }
    
    
    if (@available(iOS 11.0, *)) {
        self.mainTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    self.topSpace.constant = NavaBarHeight;
    
    [_mainTableView registerNib:[UINib nibWithNibName:@"ShenPiXiaoXiTableViewCell" bundle:nil] forCellReuseIdentifier:@"ShenPiXiaoXiTableViewCell"];
    
    [_mainTableView registerNib:[UINib nibWithNibName:@"LingQuXiaoXiTableViewCell" bundle:nil] forCellReuseIdentifier:@"LingQuXiaoXiTableViewCell"];
    
    [_mainTableView registerNib:[UINib nibWithNibName:@"QuanYuXiaoXiTableViewCell" bundle:nil] forCellReuseIdentifier:@"QuanYuXiaoXiTableViewCell"];
    
    [_mainTableView registerNib:[UINib nibWithNibName:@"LanHaiXiaoXiTableViewCell" bundle:nil] forCellReuseIdentifier:@"LanHaiXiaoXiTableViewCell"];
    
    
    
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (dataSource.count > 0) {
            NSMutableString *tempString = [NSMutableString string];
            for (NSDictionary *dataDic in dataSource) {
                if ([GetHandleString(dataDic, @"type") integerValue] == 23 ||[GetHandleString(dataDic, @"type") integerValue] == 32 ||[GetHandleString(dataDic, @"type") integerValue] == 29 ||[GetHandleString(dataDic, @"type") integerValue] == 133 ||[GetHandleString(dataDic, @"type") integerValue] == 135 ||[GetHandleString(dataDic, @"type") integerValue] == 136) {
                    
                }else{
                    if ([GetHandleString(dataDic, @"isRead") integerValue] == 0) {
                        [tempString appendString:[NSString stringWithFormat:@"%@,",GetHandleString(dataDic, @"messageId")]];
                    }
                }
            }
            
            if (tempString.length > 0) {
                NSString *result = [tempString substringToIndex:tempString.length-1];
                
                [self yiDuWithMessageId:result andIndex:10086];
            }
        }
    }];

    _mainTableView.mj_header = header;
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self upRefresh];
    }];
    _mainTableView.mj_footer = footer;
    
    page = 1;
    [self getInfoFromServer];
}
//上拉刷新
- (void)upRefresh {
    page++;
    [self getInfoFromServer];
}

//下拉刷新
- (void) downRefresh {
    page = 1;
    [self getInfoFromServer];
}

- (void)getInfoFromServer{
    
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:[NSString stringWithFormat:@"%d",page] forKey:@"page"];
    [paraDic setValue:@10 forKey:@"limit"];
   
    NSString *url = @"/adminMessage/queryList";
    [paraDic setValue:@"6" forKey:@"label"];
    
    if(_isShenPi){
        [paraDic setValue:@"3" forKey:@"label"];
    }

    [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:url andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if (!error) {
            NSLog(@"info:%@",info);
            NSArray *array = [[info objectForKey:@"data"] objectForKey:@"list"];
            if (page == 1) {
                if ([array count]> 9) {
                    dataSource = [NSMutableArray arrayWithArray:array];
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshing];
                }else {
                    dataSource = [NSMutableArray arrayWithArray:array];
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshingWithNoMoreData];
                    if(dataSource.count == 0){
                        _mainTableView.mj_footer.hidden = YES;
                    }else{
                        _mainTableView.mj_footer.hidden = NO;
                    }
                }
            }else {
                if ([array count]> 9) {
                    [dataSource addObjectsFromArray:array];
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshing];
                }else {
                    NSArray *tempArray = array;
                    if (tempArray.count > 0) {
                        [dataSource addObjectsFromArray:tempArray];
                    }
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
            
            [_mainTableView reloadData];
            
            
        }else {
            [_mainTableView.mj_header endRefreshing];
            [_mainTableView.mj_footer endRefreshing];
        }
    }];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dataDic = dataSource[indexPath.row];
    if ([GetHandleString(dataDic, @"type") intValue] == 130 || [GetHandleString(dataDic, @"type") intValue] == 131 || [GetHandleString(dataDic, @"type") intValue] == 132 || [GetHandleString(dataDic, @"type") intValue] == 133 || [GetHandleString(dataDic, @"type") intValue] == 134 || [GetHandleString(dataDic, @"type") intValue] == 0) {
        LingQuXiaoXiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LingQuXiaoXiTableViewCell"];
        AllModel *model = [[AllModel alloc] init];
        model.modelInfoDictionary = dataSource[indexPath.row];
        cell.model = model;
        
        cell.manageClickBlock = ^(NSInteger index) {
            if (index == 101) {
//                查看
                NSString *title = GetHandleString(dataDic, @"title");
                if (title.length > 0) {
                    NSArray *titleArray = [title componentsSeparatedByString:@","];
                    if (titleArray.count == 2) {
                        GongHaiKeHuXiangQingViewController *xiangQing = [[GongHaiKeHuXiangQingViewController alloc] init];
                        xiangQing.customerId = titleArray.firstObject;
                        xiangQing.poolId = titleArray.lastObject;
                        xiangQing.manageClickResultBlock = ^(NSInteger result) {
                            [self downRefresh];
                        };
                        [self pushViewController:xiangQing];
                        
                        if([GetHandleString(dataDic, @"isRead") integerValue] == 0){
                            [self yiDuWithMessageId:GetHandleString(dataDic, @"messageId") andIndex:indexPath.row];
                        }
                    }
                }
            }else if (index == 102){
//                领取
                NSString *title = GetHandleString(dataDic, @"title");
                if (title.length > 0) {
                    NSArray *titleArray = [title componentsSeparatedByString:@","];
                    if (titleArray.count == 2) {
                        [self piLiangLingQuWithUserId:@[titleArray.firstObject] andPoolId:titleArray.lastObject];
                    }
                }
            }
        };
        
        return cell;
    }
    
    
    if ([GetHandleString(dataDic, @"type") intValue] == 135 || [GetHandleString(dataDic, @"type") intValue] == 136 || [GetHandleString(dataDic, @"type") intValue] == 137) {
        
        QuanYuXiaoXiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QuanYuXiaoXiTableViewCell"];
        AllModel *model = [[AllModel alloc] init];
        model.modelInfoDictionary = dataSource[indexPath.row];
        cell.model = model;
        
        cell.manageClickBlock = ^(NSInteger index) {
            if([GetHandleString(dataDic, @"typeId") length] > 0){
                [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:[NSString stringWithFormat:@"/crmCustomer/queryByIdWithPerm/%@",GetHandleString(dataDic, @"typeId")] andParas:nil andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
                    if (!error) {
                        NSLog(@"info:%@",info);
                        
                        KeHuXiangQingViewController *shenPi = [[KeHuXiangQingViewController alloc] init];
                        shenPi.customerId = GetHandleString(dataDic, @"typeId");
                        [self pushViewController:shenPi];
                        if([GetHandleString(dataDic, @"isRead") integerValue] == 0){
                            [self yiDuWithMessageId:GetHandleString(dataDic, @"messageId") andIndex:indexPath.row];
                        }
                    }
                }];
            }
        };
        
        return cell;
    }
    
    if ([GetHandleString(dataDic, @"type") intValue] == 138 || [GetHandleString(dataDic, @"type") intValue] == 139) {
        
        LanHaiXiaoXiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LanHaiXiaoXiTableViewCell"];
        AllModel *model = [[AllModel alloc] init];
        model.modelInfoDictionary = dataSource[indexPath.row];
        cell.model = model;
        return cell;
    }

    
    ShenPiXiaoXiTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShenPiXiaoXiTableViewCell"];
    AllModel *model = [[AllModel alloc] init];
    model.isNeedShow = _isShenPi;
    model.modelInfoDictionary = dataSource[indexPath.row];
    cell.model = model;
    return cell;
}


//批量领取
- (void)piLiangLingQuWithUserId:(NSArray *)userList andPoolId:(NSString *)poolId{
    
    if(userList.count == 0){
        [ZZPUtils showWarning:@"请先选择要领取的客户"];
        return;
    }
    
    AlertRemindView *view = [AlertRemindView view];
    [ZZPUtils showAlertViewWithView:view andController:self];
    view.manageClickBlock = ^(NSInteger index) {
        [self dismissViewControllerAnimated:YES completion:^{
            if(index == 102){
    //            确定
                NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
                [paraDic setValue:userList forKey:@"ids"];
                [paraDic setValue:poolId forKey:@"poolId"];
                [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:@"/crmCustomer/receiveByIds" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
                    if(!error){
                        [self downRefresh];
                        [self shiFouLingQuChengGong:YES];
                    }else{
                        [self shiFouLingQuChengGong:NO];
                    }
                }];
            }
        }];
    };
}
//是否领取成功
- (void)shiFouLingQuChengGong:(BOOL)isSuccess{
    AlertRemindView *view = [AlertRemindView view];
    [ZZPUtils showAlertViewWithView:view andController:self];
    view.leftButton.hidden = YES;
    view.rightButton.hidden = YES;
    view.centerButton.hidden = NO;
    if(isSuccess){
        view.topImage.image = LocalImagePath(@"公海领取弹窗成功");
        view.titleLabel.text = @"领取成功";
        view.contentLabel.text = @"恭喜领取成功！";
    }else{
        view.topImage.image = LocalImagePath(@"公海领取弹窗失败");
        view.titleLabel.text = @"领取失败";
        view.contentLabel.text = @"超过库容，领取失败";
    }
    view.manageClickBlock = ^(NSInteger index) {
        [self dismissViewControllerAnimated:YES completion:nil];
    };
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    AllModel *model = [[AllModel alloc] init];
    model.isNeedShow = _isShenPi;
    model.modelInfoDictionary = dataSource[indexPath.row];
    NSDictionary *dataDic = dataSource[indexPath.row];
    if ([GetHandleString(dataDic, @"type") intValue] == 130 || [GetHandleString(dataDic, @"type") intValue] == 131 || [GetHandleString(dataDic, @"type") intValue] == 132 || [GetHandleString(dataDic, @"type") intValue] == 133 || [GetHandleString(dataDic, @"type") intValue] == 134 || [GetHandleString(dataDic, @"type") intValue] == 0) {
        return [tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[LingQuXiaoXiTableViewCell class] contentViewWidth:[self cellContentViewWith]];
    }
    
    if ([GetHandleString(dataDic, @"type") intValue] == 135 || [GetHandleString(dataDic, @"type") intValue] == 136 || [GetHandleString(dataDic, @"type") intValue] == 137) {
        return [tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[QuanYuXiaoXiTableViewCell class] contentViewWidth:[self cellContentViewWith]];
    }
    
    if ([GetHandleString(dataDic, @"type") intValue] == 138 || [GetHandleString(dataDic, @"type") intValue] == 139) {
        return [tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[LanHaiXiaoXiTableViewCell class] contentViewWidth:[self cellContentViewWith]];
    }
    
    return [tableView cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[ShenPiXiaoXiTableViewCell class] contentViewWidth:[self cellContentViewWith]];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dataDic = dataSource[indexPath.row];
    if([GetHandleString(dataDic, @"isRead") integerValue] == 0){
        [self yiDuWithMessageId:GetHandleString(dataDic, @"messageId") andIndex:indexPath.row];
    }
    if ([GetHandleString(dataDic, @"type") intValue] == 130 || [GetHandleString(dataDic, @"type") intValue] == 131 || [GetHandleString(dataDic, @"type") intValue] == 132 || [GetHandleString(dataDic, @"type") intValue] == 133 || [GetHandleString(dataDic, @"type") intValue] == 134 || [GetHandleString(dataDic, @"type") intValue] == 0) {
        return;
    }
    
    if ([GetHandleString(dataDic, @"type") intValue] == 135 || [GetHandleString(dataDic, @"type") intValue] == 136 || [GetHandleString(dataDic, @"type") intValue] == 137){
        return;
    }
    
    if ([GetHandleString(dataDic, @"typeId") length] == 0) {
        return;
    }
    if(_isShenPi){
        ShenPiXiangQingViewController *shenPi = [[ShenPiXiangQingViewController alloc] init];
        shenPi.examineId = GetHandleString(dataDic, @"typeId");
        [self pushViewController:shenPi];
        return;
    }
    KeHuXiangQingViewController *shenPi = [[KeHuXiangQingViewController alloc] init];
    shenPi.customerId = GetHandleString(dataDic, @"typeId");
    [self pushViewController:shenPi];
    
}

//消息已读
- (void)yiDuWithMessageId:(NSString *)messageId andIndex:(NSInteger)index{
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:messageId forKey:@"messageId"];
    [[ZZPRequest getWebUtil] postNetworkRequestURLString:@"/adminMessage/readMessage" andParas:paraDic andShowHud:NO andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            
          
            if (!(index == 10086 || index == 10010)) {
                NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithDictionary:dataSource[index]];
                [dataDic setValue:@"1" forKey:@"isRead"];
                [dataSource replaceObjectAtIndex:index withObject:dataDic];
                [_mainTableView reloadData];
            }
            if(_readClickBlock){
                _readClickBlock();
            }
        }
        
        if (index == 10086) {
            [self downRefresh];
        }
    }];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if (dataSource.count > 0) {
        NSMutableString *tempString = [NSMutableString string];
        for (NSDictionary *dataDic in dataSource) {
            if ([GetHandleString(dataDic, @"type") integerValue] == 23 ||[GetHandleString(dataDic, @"type") integerValue] == 32 ||[GetHandleString(dataDic, @"type") integerValue] == 29 ||[GetHandleString(dataDic, @"type") integerValue] == 133 ||[GetHandleString(dataDic, @"type") integerValue] == 135 ||[GetHandleString(dataDic, @"type") integerValue] == 136) {
                
            }else{
                if ([GetHandleString(dataDic, @"isRead") integerValue] == 0) {
                    [tempString appendString:[NSString stringWithFormat:@"%@,",GetHandleString(dataDic, @"messageId")]];
                }
            }
        }
        
        if (tempString.length > 0) {
            NSString *result = [tempString substringToIndex:tempString.length-1];
            
            [self yiDuWithMessageId:result andIndex:10010];
        }
    }
}

-(UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"暂无搜索"];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"暂无消息~"attributes: @{NSFontAttributeName: [UIFont systemFontOfSize:16],NSForegroundColorAttributeName: rgba(163, 168, 185, 1)}];
    return string;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    return YES;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end



